<template>
	<view class="cc-box">
		<picker class="ccp" @change="change" :range-key="k" :value="Index" :range="Range">
			<view :class="(!null_val && !Value) ? 'placeholder' : ''">{{find(Value)}}</view>
		</picker>
	</view>
</template>

<script>
	export default {
		name: 'ccPicker',
		props: {
			placeholder: {
				type: String,
				default: '请选择'
			},
			range: {
				type: Array,
				default: []
			},
			k: {
				type: String,
				default: 'K'
			},
			v: {
				type: String,
				default: 'V'
			},
			value: {
				type: String
			},
			null_str: {
				type: String,
				default: '',
			},
			null_val: {
				type: String,
				default: '',
			},
		},
		data() {
			return {
				Value: this.value
			}
		},
		methods: {
			change(e) {
				this.Value = this.Range[parseInt(e.target.value)][this.v];
				this.$emit('picker_change', { new_v: this.Value, new_k: this.find(this.Value) });
			},
			find() {
				if (this.Value) {
					for (var i = 0; i < this.Range.length; i++) {
						if (this.Range[i][this.v] == this.Value) {
							return this.Range[i][this.k];
						}
					}
				}
				return this.null_str ? this.null_str : this.placeholder;
			}
		},
		computed: {
			Index() {
				if (this.Value) {
					for (var i = 0; i < this.Range.length; i++) {
						if (this.Range[i][this.v] == this.Value) {
							return i;
							break;
						}
					}
				}
				return -1;
			},
			Range() {
				if(this.null_str){
					return JSON.parse(`[{"${this.k}": "${this.null_str}", "${this.v}": "${this.null_val}" }]`).concat(this.range);
				}
				else {
					return this.range;
				}
			}
		},
		watch: {
			value(newVal) {
				this.Value = newVal
			},
			Value(newVal) {
				this.$emit('input', newVal)
			}
		}
	}
</script>

<style scoped>
	.cc-box {  
	    border-bottom: 3rpx solid #e5e5e5;
		min-height: 35px;
	}
	.ccp{
		text-align: right;
		font-size: 32rpx!important;
	}
	.ccp view{
		line-height: 36rpx;
		width: calc(100% - 60upx);
		text-align: left;
		display: flex;
		height: 35px;
		align-items: center;
	}
	.placeholder {
		color: #737373;
		font-weight: 540;
	}
	.ccp:after{
		color: #ccc;
	}
</style>